package com.ruoyi.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.model.dto.UserDTO;
import com.ruoyi.model.utils.JwtUtils;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.pojo.UserEntity;
import com.ruoyi.user.result.ResultObject;
import com.ruoyi.user.utils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Description: new java files header..
 *
 * @author 兰剑
 * @version 1.0
 * @date 2023/3/5 19:38
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    
    
    /**@Description: 用户登录
     * @param userDTO
     * @return
     * @version v1.0
     * @author 兰剑
     * @date 2023/3/5 19:38
     */
    public ResultObject<UserEntity> login(UserDTO userDTO) {
         String username = userDTO.getUsername();
         String password = userDTO.getPassword();
//         前台密码加盐加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
//        加密的新密码
        String newPassword = passwordEncoder.encode(password);
//        获取查询条件
        QueryWrapper<UserEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getUsername,username);
        List<UserEntity> userEntities = userMapper.selectList(queryWrapper);
        if (userEntities==null && userEntities.size()<=0){
            return new ResultObject<>(false,"0","用户不存在",null);
        }
//        获取查询的第一条数据
        UserEntity userEntity = userEntities.get(0);
//        获取后台密码 ,进行加密
        String userEntityPassword = userEntity.getPassword();
//        密码对比
        if (!passwordEncoder.matches(userEntityPassword,newPassword)){
            return new ResultObject<>(false,"0","密码不正确",null);
        }
//        密码成功，登录成功，生成token
        String token = JwtUtils.createToken(userEntity.getUid(),userEntity.getUsername().toString(),null);
//        存入redis
        redisTemplate.opsForValue().set("token",token,30, TimeUnit.MINUTES);
//        存入hashmap返回前端
        Map map=new HashMap();
        map.put("token",token);
        map.put("userName",userEntity.getUsername());
        map.put("role",userEntity.getRoles());
        return new ResultObject(true,"1","登录成功",map);
    }

}
